from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from select import select
from urllib3 import request

from cart.models import CartModel
from cart.ser import CartSer
from course.models import CourseModel
from utils.authentication import MyAuthentication


# Create your views here.
#添加商品到购物车
class AddCart(APIView):
    authentication_classes = [MyAuthentication]
    def post(self,request):
        #判断当前用户是否该买此课程   如果买过提示用户   如果没买过添加
        data=CartModel.objects.filter(user=request.data.get('user'),course=request.data.get('course')).first()
        if data:
            return Response({"msg":'该商品已经购买！！！'})
        #没买过就添加
        ser=CartSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"msg":'添加成功'})
        return Response({"msg":ser.errors})

#商品列表
class CartList(APIView):
    authentication_classes = [MyAuthentication]
    def get(self, request):
        user=request.query_params.get('user',None)
        if user is None:
            return Response({'msg':"请传入用户id"})
        cartlist=CartModel.objects.filter(user=user)
        ser=CartSer(cartlist,many=True)
        return Response({'data':ser.data,'msg':'ok'})

class DelCart(APIView):
    authentication_classes = [MyAuthentication]
    def delete(self,request):
        id=request.GET.get('course_id')
        data=CartModel.objects.filter(id=id).first()
        data.delete()
        return Response({"msg":'ok'})

#修改单个状态
class CartUpdate(APIView):
    def put(self,request):
        id=request.data.get('id')
        select=request.data.get('select')
        info=CartModel.objects.filter(id=id).first()
        if info:
            info.selected=select
            info.save()
            return Response({'msg':"ok"})
        return Response({"msg":"没有该商品"})

#修改全部状态
class CartAll(APIView):
    def put(self,request):
        user=request.data.get('user')
        select=request.data.get('select')
        info=CartModel.objects.filter(user=user)  #queryset
        if info:
            for i in info:
                i.selected=select
                i.save()
            return Response({'msg':"ok"})
        return Response({"msg":"当前账户购物车没有该商品"})

#选中删除
class  DelAll(APIView):
    def delete(self,request):
        user=request.query_params.get('user')
        CartModel.objects.filter(user=user,selected=True).delete()
        return Response({"msg":'ok'})